//
//  HTWishViewController.m
//  HeartTravel
//
//  Created by lanou on 15/10/26.
//  Copyright © 2015年 陈文杰. All rights reserved.
//

#import "HTWishViewController.h"
#import "HTCustomLayout.h"
#import "HTWishCell.h"
#import "PKRequestManager.h"
#import "HTWishModel.h"

#import "FMDatabase.h"
#import "MJRefresh.h"

#define kURL @"http://api.daizhe.cn/v2/dream?device_type=2&ac=list&cur_version=2.3.5.1&current_date=1445653800&device_code=77FEFD37-68DD-413D-8097-32017A5C6634&device_token=21093eff1a82bf7778421dddfcf93b2e&dz_token=&dz_uid=&order=0&page=1&uid="

@interface HTWishViewController ()<HTCustomLayoutDelegate,UICollectionViewDataSource,UICollectionViewDelegate>

@property (nonatomic, strong) NSMutableArray *dataSourceArray;
@property (nonatomic, strong) UICollectionView *mainCollectionView;

@property (nonatomic, strong) FMDatabase *dataBase;

@end

@implementation HTWishViewController
{
    NSInteger _addPage;
}

+ (instancetype)shareWishVC {
    
    static HTWishViewController *wishVC = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        wishVC = [[HTWishViewController alloc] init];
    });
    return wishVC;
}

- (NSMutableArray *)dataSourceArray {
    
    if (_dataSourceArray == nil) {
        _dataSourceArray = [NSMutableArray arrayWithCapacity:0];
    }
    return _dataSourceArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    _addPage = 2;
    [self configureData];
    
    HTCustomLayout *customLayout = [[HTCustomLayout alloc] initWithNumberOfColumns:2];
    customLayout.delegate = self;
    
    _mainCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 10, SCREEN_WIDTH, SCREEN_HEIGHT-160) collectionViewLayout:customLayout];
    
    _mainCollectionView.delegate = self;
    _mainCollectionView.dataSource = self;
    _mainCollectionView.backgroundColor = [UIColor whiteColor];
    [_mainCollectionView registerClass:[HTWishCell class] forCellWithReuseIdentifier:@"cell"];
    
    
    [self.view addSubview:_mainCollectionView];
    
//    NSString *filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject stringByAppendingPathComponent:@"HeartTravel.db"];
//    _dataBase = [FMDatabase databaseWithPath:filePath];
//    if ([_dataBase open]) {
//        [_dataBase executeUpdate:@"CREATE TABLE WISH (content text, avatar text, user_name text)"];
//    } else {
//        NSLog(@"数据库打开失败");
//    }
    
//    FMResultSet *resultSet = [_dataBase executeQueryWithFormat:@"SELECT * FROM WISH "];
//    while ([resultSet next]) {
//        NSString *content = [resultSet stringForColumn:@"content"];
//        NSString *avatar = [resultSet stringForColumn:@"avatar"];
//        NSString *user_name = [resultSet stringForColumn:@"user_name"];
//        
//        HTWishModel *model = [[HTWishModel alloc] init];
//        model.content = content;
//        model.avatar = avatar;
//        model.user_name = user_name;
//        [self.dataSourceArray addObject:model];
//    }
//    [resultSet close];
    
    // 李明杰下拉刷新
//    __weak HTWishViewController *wishVC = self;
//    _mainCollectionView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
//        [wishVC configureData];
//        [_mainCollectionView.header endRefreshing];
//    }];
//
//    _mainCollectionView.footer = [MJRefreshAutoFooter footerWithRefreshingBlock:^{
//        [wishVC configureMoreData];
//        [_mainCollectionView.footer endRefreshing];
//        _addPage++;
//    }];
}

- (void)configureData{
    
    [PKRequestManager requestWithType:GET urlString:kURL parDic:nil finish:^(NSData *data) {
//        [_dataBase executeUpdate:@"DELETE FROM WISH"];
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers|NSJSONReadingMutableLeaves error:nil];
        [self.dataSourceArray removeAllObjects];
        for (NSDictionary *modelDic in dict[@"responseData"][@"list"]) {
            HTWishModel *model = [[HTWishModel alloc] init];
            [model setValuesForKeysWithDictionary:modelDic];
            [self.dataSourceArray addObject:model];
            
//            [_dataBase executeUpdate:@"INSERT INTO WISH (content, avatar, user_name) VALUES (?,?,?)", model.content, model.avatar, model.user_name];
        }
        [self.mainCollectionView reloadData];
        
    } error:^(NSError *error) {
        NSLog(@"请求失败");
    }];
}

- (void)configureMoreData {
    
    NSString *urlStr = [@"http://api.daizhe.cn/v2/dream?device_type=2&ac=list&cur_version=2.3.5.1&current_date=1445653800&device_code=77FEFD37-68DD-413D-8097-32017A5C6634&device_token=21093eff1a82bf7778421dddfcf93b2e&dz_token=&dz_uid=&order=0&page=" stringByAppendingFormat:@"%ld%@", _addPage, @"&uid="];
    [PKRequestManager requestWithType:GET urlString:urlStr parDic:nil finish:^(NSData *data) {
   
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers|NSJSONReadingMutableLeaves error:nil];
        for (NSDictionary *modelDic in dict[@"responseData"][@"list"]) {
            HTWishModel *model = [[HTWishModel alloc] init];
            [model setValuesForKeysWithDictionary:modelDic];
            [self.dataSourceArray addObject:model];
        }
        [self.mainCollectionView reloadData];
        
    } error:^(NSError *error) {
        NSLog(@"请求失败");
    }];
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(HTCustomLayout *)layout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    HTWishModel *model = _dataSourceArray[indexPath.item];
    CGFloat width = SCREEN_WIDTH/2;
    CGFloat height = [HTWishViewController heightForString:model.content]+60;
    return CGSizeMake(width, height);
}

#pragma mark - UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    return self.dataSourceArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    HTWishCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    HTWishModel *model = self.dataSourceArray[indexPath.item];
    [cell setConfigureModel:model];
    return cell;
}

+ (CGFloat)heightForString:(NSString *)str {
    
    CGRect bounds = [str boundingRectWithSize:CGSizeMake(SCREEN_WIDTH/2-20, 0) options:NSStringDrawingUsesLineFragmentOrigin attributes:[NSDictionary dictionaryWithObject:[UIFont systemFontOfSize:15] forKey:NSFontAttributeName] context:nil];
    return bounds.size.height;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
